package com.fasteat.mall.controller;

import com.fasteat.common.entity.Result;
import com.fasteat.mall.entity.dto.PayDto;
import com.fasteat.mall.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 白sa能
 * @className
 * @date Created in 4:56 PM 2/10/21
 * @package com.fasteat.mall.controller
 * @Description
 */
@Api(description = "付款接口")
@RestController
@CrossOrigin
@RequestMapping("/mall/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    /**
     * 付款
     *
     * @param payDto payDto
     * @return Result
     */
    @ApiOperation(value = "支付接口")
    @PostMapping(value = "/charge")
    public Result charge(@RequestBody PayDto payDto){
        //payDto就是你前端传过来的值,比如充值金额是多少 用户id是多少..
        //这个实体类根据你们自己的业务需求去写就好
        String orderString = paymentService.order(payDto);
        return Result.success("支付成功").data(orderString);
    }

    /**
     * 支付宝支付成功后.异步请求该接口
     *
     * @param request
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "支付异步接口，前端测试时无需理会")
    @RequestMapping(value="/aliNotify",method= RequestMethod.POST)
    @ResponseBody
    public Result aliNotify(HttpServletRequest request) throws IOException {
        //支付宝异步返回支付结果开始
        //1.从支付宝回调的request域中取值
        //获取支付宝返回的参数集合
        Map<String, String[]> aliParams = request.getParameterMap();
        //用以存放转化后的参数集合
        Map<String, String> conversionParams = new HashMap<String, String>();
        for (Iterator<String> iter = aliParams.keySet().iterator(); iter.hasNext(); ) {
            String key = iter.next();
            String[] values = aliParams.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
            conversionParams.put(key, valueStr);
        }
        return paymentService.aliNotify(conversionParams)? Result.success("支付成功") : Result.error("支付失败");

    }
}
